package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class DelMRitem
 */ 
public class QuerySubsysSquad extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QuerySubsysSquad() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		Widgets wid = new Widgets();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String strSQL = "SELECT t1.squadid, t1.subsysid, t1.squadname,t2.subsysname FROM squad t1,subsys t2 WHERE t1.subsysid=t2.subsysid";
		ArrayList<InfoStruc> infoStrucs = new ArrayList<InfoStruc>();
		
		try {
			conn = wid.getConn(true);	
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			while (rs.next()) {
				InfoStruc infoStruc = new InfoStruc();
				infoStruc.setId(rs.getString("subsysname")+"("+rs.getString("subsysid")+")");	//借用ID為子系統
				infoStruc.setName(rs.getString("squadname")+"("+rs.getString("squadid")+")");	//借用Name為Squad
				infoStrucs.add(infoStruc);
			}
		} catch ( SQLException e) {
			System.out.println(wid.errProcess(e));
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}
		
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(new Gson().toJson(infoStrucs));
	}
}